#include "networkwidget.h"
#include "ui_networkwidget.h"
#include <QDebug>

NetworkWidget::NetworkWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::networkwidget)
{
    ui->setupUi(this);
    label_7 = ui->label_7; // 初始化label_7
    // 初始化时指定父部件为当前 Widget
    client = new TCP_client(this);
    server = new tcp_server(this);

    // 设定初始模式
    this->client_or_server = ui->comboBox->itemText(ui->comboBox->currentIndex());
    qDebug() << ui->comboBox->itemText(ui->comboBox->currentIndex());

    // 清空输入框的数据
    ui->lineEdit->clear();
    ui->lineEdit_2->clear();

    // 手动关联 pushButton_3 的 clicked 信号到槽函数
    connect(ui->pushButton_3, &QPushButton::clicked, this, &NetworkWidget::on_pushButton_3_clicked);

    // 客户端接收消息时转发
    connect(client, &TCP_client::read_sig, this, [&](QString message)
    {
        qDebug() << "接收到信息: " << message;
        ui->textEdit->setText(ui->textEdit->toPlainText() + message);
        // 新增：转发接收的消息
        emit receivedNetworkMessage(message);}
    );

    // 服务器接收消息时转发
    connect(server, &tcp_server::recv_sig, this, [&](QString smg)
    {
        ui->textEdit->setText(ui->textEdit->toPlainText() + smg);
        // 新增：转发接收的消息
        emit receivedNetworkMessage(smg);}
    );
}

NetworkWidget::~NetworkWidget()
{
    delete ui;
}



void NetworkWidget::on_pushButton_2_clicked()
{
    // 按钮文本固定为"连接"（或根据状态显示，但不处理断开）
        ui->pushButton_2->setText("连接");

        // 连接 TCP 客户端
        if (ui->comboBox->currentText() == "TCP客户端")
        {
            // 关键：判断当前状态，避免重复连接
                    if (client->isConnected() || client->isConnecting())
                    {
                        qDebug() << "已连接或正在连接，无需重复操作";
                        return; // 直接返回，不执行后续连接
                    }
            qDebug() << "发起TCP客户端连接";
            // 设定连接参数
            client->set_connect(ui->lineEdit->text(), ui->lineEdit_2->text().toUInt());
            //client->start_connect();
            // 启动连接
            client->start_connect();// 仅在未连接时调用

            // 连接信号（只绑定一次，避免重复绑定）
            static bool clientSignalsConnected = false;
            if (!clientSignalsConnected)
            {
                connect(client, &TCP_client::connect_sig, this, [&](){
                    qDebug() << "客户端连接成功";
                    label_7->setText("网络已连接");
                    emit connectionStatusChanged("网络已连接"); // 新增：发射连接状态信号
                });
                connect(client, &TCP_client::dis_connect_sig, this, [&](){
                    qDebug() << "客户端连接断开";
                    label_7->setText("网络未连接");
                    emit connectionStatusChanged("网络未连接"); // 新增：发射连接状态信号
                });
                connect(client, &TCP_client::read_sig, this, [&](QString message){
                    qDebug() << "接收到信息: " << message;
                    ui->textEdit->setText(ui->textEdit->toPlainText() + message);
                });
                clientSignalsConnected = true;
            }
        }
        // 启动 TCP 服务器
        else if (ui->comboBox->currentText() == "TCP服务器")
        {
            qDebug() << "启动TCP服务器监听";
            // 启动监听
            server->listen(ui->lineEdit_2->text().toUInt());

            // 绑定信号（只绑定一次，避免重复绑定）
            static bool serverSignalsConnected = false;
            if (!serverSignalsConnected)
            {
                connect(server, &tcp_server::recv_sig, this, [&](QString smg){
                    ui->textEdit->setText(ui->textEdit->toPlainText() + smg);
                });
                serverSignalsConnected = true;
            }
        }
    }

// 选择为 客户端 还是 服务器
void NetworkWidget::on_comboBox_currentIndexChanged(const QString &arg1)
{
    this->client_or_server = arg1;
    qDebug() << ui->comboBox->itemText(ui->comboBox->currentIndex());


}

void NetworkWidget::on_pushButton_clicked()
{
    // 连接 TCP 客户端
    if(ui->comboBox->itemText(ui->comboBox->currentIndex()) == "TCP客户端")
    {
        // 发送数据
        client->send_msg(ui->lineEdit_3->text());

        ui->textEdit->setText(ui->textEdit->toPlainText() + ui->lineEdit_3->text());
    }
}

void NetworkWidget::on_pushButton_3_clicked()
{
    if (ui->comboBox->currentText() == "TCP客户端")
    {
        client->disconnectFromHost(); // 调用公共方法
    }
    else if (ui->comboBox->currentText() == "TCP服务器")
    {
        server->disconnectClient(); // 调用公共方法
    }

    label_7->setText("网络未连接");
    ui->pushButton_2->setText("连接");
}

//"返回上一页按钮"
void NetworkWidget::on_pushButton_4_clicked()
{
    emit switchToRemoteControl(); // 发射信号
}
